

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.swing.JTextArea;
import javax.swing.SwingWorker;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;



/**
 * Searches the text files under the given directory and counts the number of instances a given word is found in these
 * file.
 * 
 * @author Albert Attard
 */
public class SearchForWordWorker extends SwingWorker<Integer, String> {

	
 
  
  
  
  private StandardAnalyzer analyzer;
  
  private String indexDir;

  /** The word that is searched */
  private final String word;

  /** The directory under which the search occurs. All text files found under the given directory are searched. */
  //private final File directory;

  /** The text area where messages are written. */
  private final JTextArea messagesTextArea;

  /**
   * Creates an instance of the worker
   * 
   * @param word
   *          The word to search
 * @param path 
   * @param directory
   *          the directory under which the search will occur. All text files found under the given directory are
   *          searched
   * @param messagesTextArea
   *          The text area where messages are written
   */
  public SearchForWordWorker(final String word, String indexPath, final JTextArea messagesTextArea, StandardAnalyzer analyzer, Directory index) {
    this.word = word;
    this.messagesTextArea = messagesTextArea;
    this.analyzer = analyzer;
    this.indexDir = indexPath;
  
  }
  


  @Override
  protected Integer doInBackground() throws Exception {
	  
	  
	  
	  
    // The number of instances the word is found
    //int matches = 0;

//    /*
//     * List all text files under the given directory using the Apache IO library. This process cannot be interrupted
//     * (stopped through cancellation). That is why we are checking right after the process whether it was interrupted or
//     * not.
//     */
//    publish("Listing all text files under the directory: " + directory);
//    final List<File> textFiles = new ArrayList<>(FileUtils.listFiles(directory, new SuffixFileFilter(".txt"),
//        TrueFileFilter.TRUE));
//    SearchForWordWorker.failIfInterrupted();
//    publish("Found " + textFiles.size() + " text files under the directory: " + directory);
//
//    for (int i = 0, size = textFiles.size(); i < size; i++) {
//      /*
//       * In order to respond to the cancellations, we need to check whether this thread (the worker thread) was
//       * interrupted or not. If the thread was interrupted, then we simply throw an InterruptedException to indicate
//       * that the worker thread was cancelled.
//       */
//      SearchForWordWorker.failIfInterrupted();
//
//      // Update the status and indicate which file is being searched.
//      final File file = textFiles.get(i);
//      publish("Searching file: " + file);
//
//      /*
//       * Read the file content into a string, and count the matches using the Apache common IO and Lang libraries
//       * respectively.
//       */
//      final String text = FileUtils.readFileToString(file);
//      matches += StringUtils.countMatches(text, word);
//
//      // Update the progress
//      setProgress((i + 1) * 100 / size);
//    }

    
    	// 1. create the index
 		//index = new RAMDirectory();

 		

 		// =========================================================
 		// Now search
 		// =========================================================
 		IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(
 				indexDir)));
 		IndexSearcher searcher = new IndexSearcher(reader);
 		publish("Searching ...");
 		
 		TopScoreDocCollector collector = TopScoreDocCollector.create(5, true);

 		Query q = new QueryParser(Version.LUCENE_46, "contents", analyzer)
 				.parse(word);
 		searcher.search(q, collector);
 		ScoreDoc[] hits = collector.topDocs().scoreDocs;

 		// 4. display results
 		publish("Found " + hits.length + " hits:");
 		for (int i = 0; i < hits.length; ++i) {
 			int docId = hits[i].doc;
 			Document d = searcher.doc(docId);
 			publish((i + 1) + ". " + d.get("path") + " score=" + hits[i].score);
 		}
 		
 		publish("\n"+ "--------------------------------------------"+"\n\n");
 		
    
    // Return the number of matches found
 		return hits.length;
  }

  @Override
  protected void process(final List<String> chunks) {
    // Updates the messages text area
    for (final String string : chunks) {
      messagesTextArea.append(string);
      messagesTextArea.append("\n");
    }
  }
  
  private static void failIfInterrupted() throws InterruptedException {
	    if (Thread.currentThread().isInterrupted()) {
	      throw new InterruptedException("Interrupted while searching files");
	    }
	  }
}
